import React, { useState } from "react";
import { Form, Input, Button, Toast } from "antd-mobile";
import request from "../../utils/request";
import { useNavigate, useSearchParams } from "react-router-dom";
const Login = () => {
  const [tel, setTel] = useState("");
  const [form] = Form.useForm();
  const [count, setCount] = useState(60);
  const navigate=useNavigate()
  // const [searchParams]=useSearchParams()

  const getCode = async () => {
    // 实现点击获取验证码时校验手机号必填且必须是11位数字
    const reg = /^1[3-9]\d{9}$/;
    if (!reg.test(tel) || tel === "") {
      Toast.show({
        icon: "fail",
        content: "手机号格式不正确",
      });
      return;
    }

    // 9-3.点击获取验证码后，按钮内容变成倒计时60s，并能实现倒计时功能
    let timer;
    let num = 60;
    timer = setInterval(() => {
      num--;
      setCount((prev) => prev - 1);
      if (num == 0) {
        clearInterval(timer);
        setCount(60);
      }
    }, 1000);

    // 9-2.调接口获取随机验证码的接口，将响应回来的验证码自动填充到验证码输入框中
    const res = await request.get("/login/login/code", {
      params: { tel },
    });
    form.setFieldValue("telCode", res.data.data);
  };

  const onFinish=async(value)=>{
    const res=await request.post('/login/login/tel',value)
    // 登录接口返回成功之后本地存储token，跳转到我的页面
    if(res.data.code===200){
        Toast.show({
            icon:'success',
            content:'登录成功'
        })
        const token= res.data.data.token
        localStorage.setItem('token',token)
        // if(searchParams.get('from')){
        //     navigate(searchParams.get('from'))
        // }else{
            
        // }
        // const form=searchParams.get('from')
        // console.log(form)
        navigate('/my')
       
    }
    
  }
  return (
    <div>
      <Form
        form={form}
        onFinish={onFinish}
        layout="horizontal"
        footer={
          <Button block type="submit" color="primary" size="large">
            提交
          </Button>
        }
      >
        <Form.Header>
          <h1>手机号码登录</h1>
        </Form.Header>
        <Form.Item
          name="tel"
          label="手机号码"
        //   登录时验证手机号，未写提示错误
          rules={[{ required: true, message: "手机号码不能为空" }]}
        >
          <Input
            value={tel}
            onChange={(e) => setTel(e)}
            placeholder="请输入手机号码"
          />
        </Form.Item>
        <Form.Item
          name="telCode"
          label="验证码"
          extra={
            <a onClick={getCode}>
              {count == 60 ? "获取验证码" : `${count}s后重试`}
            </a>
          }
        //   登录时验证码必填，未写提示错误
          rules={[{ required: true, message: "验证码不能为空" }]}
        >
          <Input placeholder="请输入验证码" />
        </Form.Item>
      </Form>
    </div>
  );
};

export default Login;
